import { constantRoutes } from '@/router' // asyncRoutes,
import Layout from '@/layout/index'
import Layout1 from '@/layout1/index'
import {
  getBuild
} from "@/api/case.js"; 

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

function getUrlKey(val) {
  return decodeURIComponent((new RegExp('[?|&]' + val + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // commit('SET_ROUTES', [])
      // resolve([])
      // 获取菜单
      // if ( getUrlKey('app') == 1) {?application=1
        getBuild({application:getUrlKey('app')}).then(result => {
          // console.log('获取菜单', result)
          const res = filterAsyncRouter(result.data)
          let accessedRoutes
          if (roles.includes('admin')) {
            accessedRoutes = constantRoutes || []
          } else {
            accessedRoutes = filterAsyncRoutes(constantRoutes, roles)
          }
          commit('SET_ROUTES', res)
          resolve(res)
        })
        
      // }else if ( getUrlKey('app') == 2){
      //   commit('SET_ROUTES', [])
      //   resolve([])
      // }

    })
  }
}



export const filterAsyncRouter = (routers) => { // 遍历后台传来的路由字符串，转换为组件对象

  let route;
  if (!Array.isArray(routers)) {
    route = routers.data
  } else {
    route = routers
  }
  return route.filter(router => {
    //   if ( getUrlKey('app') == 1) {
    // } else if ( getUrlKey('app') == 2) {
    //     constantRoutes = constantRoutes1
    // }

    if (router.component) {
      if (router.component === 'Layout1') { // Layout组件特殊处理
        router.component = Layout1
      } else if (router.component === 'Layout') {
        router.component = Layout
      } else {
        const component = router.component
        router.component = loadView(component)
        // console.log(router.component)
      }
    }
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children)
    }
    return true
  })
}

export const loadView = (view) => {
  // debugger
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
